package model

import (
	"ReaderInOutLog/logger"
	"fmt"
	"time"
)

var Logger, _ = logger.ConfigureLogger()

type ReaderInOutLog struct {
	ID          int       `xorm:"pk autoincr 'nID'"`
	RecordTime  time.Time `xorm:"'dtRecordTime'"`
	Type        int       `xorm:"'nType'"`
	Counter     int       `xorm:"not null default 0 'nCounter'"`
	JanitorName string    `xorm:"'szJanitorName'"`
	ReaderID    string    `xorm:"'szReaderID'"`
}

func (r *ReaderInOutLog) TableName() string {
	return "ReaderINOUTLog"
}

// GetBook retrieves a record by ID from the database.
func GetReaderInOutLog(id int) (*ReaderInOutLog, int) {
	record := new(ReaderInOutLog)
	has, err := db.ID(id).Get(record)
	if err != nil {
		fmt.Printf("Error getting record: %v", err)
		return nil, 500
	}
	if !has {
		return nil, 404
	}
	return record, 200
}

func GetReaderInOutLogByIds(id int) ([]*ReaderInOutLog, int) {
	var records []*ReaderInOutLog
	err := db.Where("nID >?", id).Find(&records)
	if err != nil {
		return nil, 500
	}
	return records, 200
}

// UpdateBook updates a record in the database.
func UpdateReaderInOutLog(newRecord *ReaderInOutLog) int {
	session := db.NewSession()
	// defer session.Close()
	if err := session.Begin(); err != nil {
		return 500
	}
	_, err := session.ID(newRecord.ID).Update(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return 500
		}
		return 500
	}
	if err := session.Commit(); err != nil {
		return 500
	}
	return 200
}

// edit
func EditReaderInOutLog(newRecord *ReaderInOutLog) int {
	session := db.NewSession()
	// defer session.Close()
	if err := session.Begin(); err != nil {
		return 500
	}
	_, err := session.ID(newRecord.ID).Update(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return 500
		}
	}
	if err := session.Commit(); err != nil {
		return 500
	}
	return 200
}

// delete
func DeleteReaderInOutLog(id int) int {
	session := db.NewSession()
	// defer session.Close()
	if err := session.Begin(); err != nil {
		return 500
	}
	_, err := session.ID(id).Delete(&ReaderInOutLog{})
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return 500
		}
		return 500
	}
	return 200
}
func InsertReaderInOutLog(newRecord *ReaderInOutLog) int {
	session := db.NewSession()
	// defer session.Close()
	if err := session.Begin(); err != nil {
		Logger.Errorf("Error inserting record: %v", err)
		return 500
	}
	_, err := session.Insert(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			Logger.Errorf("Error inserting record: %v", err)
			return 500
		}
		return 500
	}
	if err := session.Commit(); err != nil {
		Logger.Errorf("Error inserting record: %v", err)
		return 500
	}
	return 200
}

func InsertReaderInOutLog2(newRecord *ReaderInOutLog) int {
	t := newRecord.RecordTime.Format("2006-01-02 15:04:05.000")
	smt := fmt.Sprintf("insert into ReaderINOUTLog(dtRecordTime,nType,nCounter,szJanitorName,szReaderID) values('%s',%d,%d,'%s','%s')", t, newRecord.Type, newRecord.Counter, newRecord.JanitorName, newRecord.ReaderID)
	// sql = "update `userinfo` set username=? where id=?"
	// res, err := engine.Exec(sql, "xiaolun", 1)
	res, err := db.Exec(smt)
	if err != nil {
		lg.Errorf("Error inserting record: %v", err)
		return 500
	}
	lg.Debugf("insert res is %v", res)
	return 200
}

// 根据RecordTime时间查询当天和JanitorName的对象
func GetReaderInOutLogByTime(recordTime string, janitorName string) ([]*ReaderInOutLog, int) {
	var records []*ReaderInOutLog
	err := db.Where("dtRecordTime > ? AND szJanitorName = ?", recordTime, janitorName).Find(&records)
	if err != nil {
		lg.Debugf("GetReaderInOutLogByTime Error getting record: %v", err)
		return nil, 500
	}
	return records, 200
}

func GetReaderInOutLogALL(janitorName string, page int, pageSize int) ([]*ReaderInOutLog, int, int) {

	var records []*ReaderInOutLog
	offset := (page - 1) * pageSize
	err = db.Where("szJanitorName =?", janitorName).Limit(pageSize, offset).Find(&records)
	if err != nil {
		lg.Debugf("GetReaderInOutLogByTime Error getting record: %v", err)
		return nil, 500, 0
	}
	totalRecords, err := db.Where("szJanitorName =?", janitorName).Count(new(ReaderInOutLog))
	if err != nil {
		lg.Debugf("Error getting total records: %v", err)
		return nil, 500, 0
	}
	return records, 200, int(totalRecords)
}

// 获取max(id)
func GetMaxID() (int, int) {
	var record ReaderInOutLog
	has, err := db.OrderBy("nID desc").Get(&record)
	if err != nil {
		lg.Errorf("Error getting record: %v", err)
		return 0, 500
	}
	lg.Debugf("has is %v", has)
	return record.ID, 200
}

//获取szJanitorName

// 清空表
func ClearData() {
	db.DropTables(&ReaderInOutLog{})
	db.CreateTables(&ReaderInOutLog{})
}
